<template>
	<view class="my-picker flexc">
		<picker-view class="flex-1 flexr justify-space-around" @change="onPickerChange">
			<picker-view-column class="picker-column">
				<view class="picker-row" v-for="(item, index) in mapProvinces" :key="index">
					{{item.fullname}}
				</view>
			</picker-view-column>
			<picker-view-column class="picker-column">
				<view class="picker-row" v-for="(item, index) in mapCities" :key="index">
					{{item.fullname}}
				</view>
			</picker-view-column>
			<picker-view-column class="picker-column">
				<view class="picker-row" v-for="(item, index) in mapDistricts" :key="index">
					{{item.fullname}}
				</view>
			</picker-view-column>
		</picker-view>
		<view class="btns flexr justify-center">
			<view class="btn cancel-button" @click="emits('onCancel')">
				取消
			</view>
			<view class="btn primary-button" @click="emits('onConfirm')">
				确定
			</view>
		</view>
	</view>
</template>

<script setup>
import { computed, ref } from 'vue';
import { useSysStore } from '@/store/sys';
const sysStore = useSysStore();

const pindex = ref(0);
const cindex = ref(0);
const dindex = ref(0);

const mapProvinces = computed(() => sysStore.provinces);

const mapCities = computed(() => {
	const selectedProvince = sysStore.provinces[pindex.value];
	if (!selectedProvince) return [];
	if (!selectedProvince.cidx) return [selectedProvince];
	const [scidx, ecidx] = selectedProvince.cidx;
	return sysStore.cities.filter((city, index) => index >= scidx && index <= ecidx);
});

const mapDistricts = computed(() => {
	const selectedCity = mapCities.value[cindex.value];
	if (!selectedCity) return [];
	if (!selectedCity.cidx) return [selectedCity];
	const [scidx, ecidx] = selectedCity.cidx;
	return sysStore.districts.filter((district, index) => index >= scidx && index <= ecidx);
});

const emits = defineEmits(['onCancel', 'onConfirm'])

function onPickerChange({detail}) {
	const [p, c, d] = detail.value;
	console.log(detail.value)
	pindex.value = p;
	cindex.value = c;
	dindex.value = d;
}
</script>

<style lang="scss">
.my-picker {
	height: 480rpx;
	box-sizing: border-box;
	background-color: white;
	overflow: hidden;
	border-top-right-radius: 30rpx;
	border-top-left-radius: 30rpx;
	padding-top: 15rpx;
	.picker-column {
		width: 200rpx;
	}
	.picker-row {
		height: 80rpx;
		text-align: center;
	}
	.btns {
		margin-top: 20rpx;
		.btn {
			width: 300rpx;
			margin-top: 0 !important;
		}
		.btn + .btn {
			margin-left: 30rpx;
		}
	}
}
</style>
